﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Onetube.Entities.CategorieQuery;
using Onetube.Providers.Interfaces;

namespace Onetube.Providers
{
    public class YoutubeCategoryProvider : IYoutubeCategoryProvider
    {
        public Task<Onetube.Entities.CategorieQuery.CategorieQueryResult> GetAllCategories(string hl, string regionCode, CancellationTokenSource cancelTask)
        {
            StringBuilder petitionUri = new StringBuilder("https://www.googleapis.com/youtube/v3/videoCategories?");

            petitionUri.AppendFormat("part={0}", "snippet");
            petitionUri.AppendFormat("&hl={0}", hl);
            petitionUri.AppendFormat("&regionCode={0}", regionCode);
       
            petitionUri.AppendFormat("&key={0}", AppKeys.API_KEY);

            var taskCompletitionSource = new TaskCompletionSource<CategorieQueryResult>();

            return ResolveRequest(petitionUri, taskCompletitionSource,cancelTask);
        }

        private Task<CategorieQueryResult> ResolveRequest(StringBuilder petitionUri, TaskCompletionSource<CategorieQueryResult> taskCompletitionSource, CancellationTokenSource cancelTask)
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(petitionUri.ToString());

            request.BeginGetResponse(async result =>
            {
                if (result.IsCompleted)
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

                        string resultJson;

                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            resultJson = await reader.ReadToEndAsync().ConfigureAwait(false);
                        }

                        if (!string.IsNullOrEmpty(resultJson))
                        {
                            var entries = JsonConvert.DeserializeObject<CategorieQueryResult>(resultJson);

                            taskCompletitionSource.SetResult(entries);
                            resultJson = null;
                            entries = null;
                          
                        }
                              response.Dispose();
                    }
                    catch (Exception ex)
                    {
                        taskCompletitionSource.SetException(ex);
                    }

                }

            }, null);

            return taskCompletitionSource.Task;
        }
    }
}